<template>
  <div>
    <el-select-tree
      :style="{ width: selectConfig.width || '100%' }"
      :placeholder="selectConfig.placeholder"
      :data="treeList"
      @change="selectChange"
      :default-expand-all="selectConfig.defaultExpandAll"
      :multiple="selectConfig.multiple || false"
      :props="selectConfig.props"
      :node-key="selectConfig.nodeKey || 'id'"
      v-model="selectedValue"
    ></el-select-tree>
  </div>
</template>

<script>
export default {
  name: "VueAutoSelect",
  props: {
    apiUrl: {
      type: Function,
      required: true,
    },
    value: {
      required: true,
    },
    otherConfig: {
      // 其他配置参数
      type: Object,
      default: () => {},
    },
    defaultFiled: {
      //默认获取列表数据的字段
      type: String,
      default: () => "data",
    },
  },
  data() {
    return {
      treeList: [],
    };
  },
  computed: {
    selectedValue: {
      get() {
        return this.value;
      },
      set() {},
    },
    selectConfig() {
      const obj = {
        placeholder: "请选择",
        filterable: false,
        disabled: false,
        multiple: false,
        valueKey: null,
        defaultExpandAll: true,
        style: { width: "100%" },
        nodeKey: "id",
        props: { label: "label", children: "children" },
        clearable: true,
      };
      return { ...obj, ...this.otherConfig };
    },
  },
  watch: {},

  mounted() {
    if (this.apiUrl) this.fetchOptions();
  },
  methods: {
    selectChange(e) {
      this.$emit("update:value", e);
      this.$emit("change", e);
    },
    fetchOptions() {
      this.apiUrl()
        .then((response) => {
          const {
            otherConfig: { defaultVal },
            defaultFiled,
          } = this;
          const data = response?.[defaultFiled];
          console.log(data, "---fetchOptions");
          if (data && Array.isArray(data)) {
            this.treeList = data;
          }
        })
        .catch((error) => {
          console.error("Failed to fetch options:", error);
        });
    },
  },
};
</script>
